package com.youlu.campus.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.google.common.collect.Lists;
import com.youlu.campus.entity.ActivityInfo;
import com.youlu.campus.entity.ActivityOrganizerInfo;
import com.youlu.campus.entity.ActivityQaInfo;
import com.youlu.campus.entity.ActivityQuestionInfo;
import com.youlu.campus.entity.ActivityTaskInfo;
import com.youlu.campus.entity.FileExportTask;
import com.youlu.campus.entity.UniversityBaoMingStatistics;
import com.youlu.campus.entity.UniversityInfo;
import com.youlu.campus.entity.UserActivityFootPrint;
import com.youlu.campus.entity.UserInviteRecord;
import com.youlu.campus.entity.UserParticipateActivityInfo;
import com.youlu.campus.entity.UserQaInfo;
import com.youlu.campus.entity.VO.res.ExportUserActivitySignUpRes;
import com.youlu.campus.entity.english.UserCompetitionQaAnswer;
import com.youlu.campus.entity.enums.TaskBizType;
import com.youlu.campus.service.activity.ActivityService;
import com.youlu.campus.service.clock.UserClockService;
import com.youlu.campus.service.file.FileExportTaskService;
import com.youlu.campus.service.file.FileService;
import com.youlu.campus.service.organizer.ActivityOrganizerInfoService;
import com.youlu.campus.service.qa.ActivityQaInfoService;
import com.youlu.campus.service.visitor.UserBlackListService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.FindAndModifyOptions;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AdminExportUserSignUpService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private FileExportTaskService fileExportTaskService;

    @Autowired
    private ActivityService activityService;

    @Autowired
    private FileService fileService;

    @Autowired
    private UserClockService userClockService;

    private final static String MOBILE = "mobile:%s";

    private final Integer MAX_COUNT = 500000;

    @Autowired
    private ActivityOrganizerInfoService activityOrganizerInfoService;

    @Autowired
    private UserBlackListService userBlackListService;

    @Autowired
    private ActivityQaInfoService activityQaInfoService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 统计学校报名人数
     */
    public void doUniversityBaoMingStatistics() {
        Integer currentPageNo = 1;
        Integer pageSize = 50000;
        log.info("【统计学校报名人数】start");
        while (true) {
            AtomicReference<Query> query = new AtomicReference<>(new Query());
            query.get().addCriteria(Criteria.where("joined").is(Boolean.TRUE));
            query.get().addCriteria(Criteria.where("universityId").exists(Boolean.TRUE));
            Pageable pageRequest = PageRequest.of(currentPageNo - 1, pageSize);
            List<UserParticipateActivityInfo> list = this.mongoTemplate.find(query.get().with(pageRequest),
                    UserParticipateActivityInfo.class);
            if (CollectionUtils.isEmpty(list)) {
                log.warn("【结束】当前第 {} 页结束", currentPageNo);
                break;
            }
            Map<String, List<UserParticipateActivityInfo>> userUniversityMap =
                    list.stream().collect(Collectors.groupingBy(UserParticipateActivityInfo::getUniversityId));
            userUniversityMap.forEach((universityId, item) -> {
                log.info(">>>>>>学校 universityId ->{}", universityId);
                UniversityInfo universityInfo = this.mongoTemplate.findById(universityId, UniversityInfo.class);
                item.stream().forEach(user -> {
                    if (StringUtils.isNotBlank(user.getMobile()) && StringUtils.isNotBlank(user.getUniversityId())) {
                        String formatMobile = String.format(MOBILE, user.getMobile());
                        if (!redisTemplate.hasKey(formatMobile)) {
                            redisTemplate.opsForValue().set(formatMobile, user.getMobile());
                            redisTemplate.expire(formatMobile,  72L, TimeUnit.SECONDS);
                            query.set(new Query());
                            query.get().addCriteria(Criteria.where("universityId").is(user.getUniversityId()));
                            Update update = new Update();
                            update.set("universityName", user.getUniversityName());
                            if (Objects.nonNull(universityInfo)) {
                                update.set("province", universityInfo.getProvince());
                            }
                            update.inc("count", 1);
                            FindAndModifyOptions findAndModifyOptions = new FindAndModifyOptions();
                            findAndModifyOptions.upsert(Boolean.TRUE);
                            findAndModifyOptions.returnNew(Boolean.TRUE);
                            mongoTemplate.findAndModify(query.get(), update, findAndModifyOptions,
                                    UniversityBaoMingStatistics.class);
                        }
                    }
                });
            });
            userUniversityMap.clear();
            currentPageNo++;
            log.warn("【统计学校报名人数】当前第 {} 页", currentPageNo);
        }
        log.info("【统计学校报名人数】end");
    }


    /**
     * 导出报名用户
     *
     * @param
     * @returngetPayConfig
     */
    public void exportUserV2(String activityId, String optName, String userId,
                             String key, Integer invitedNumStart, Integer invitedNumEnd) {
        log.info("start 【导出报名用户】optName ->{}| activityId ->{} | userId ->{} key->{}", optName, activityId, userId, key);
        Query query = new Query();
        query.addCriteria(Criteria.where("activityId").is(activityId).and("joined").is(Boolean.TRUE));
        if (StringUtils.isNotBlank(key)) {
            query.addCriteria(new Criteria().orOperator(Criteria.where("name").is(key),
                    Criteria.where("mobile").is(key)));
        }
        Criteria criteriaInvitedNum = null;
        if (invitedNumStart != null || invitedNumEnd != null) {
            criteriaInvitedNum = Criteria.where("invitedNum");
            if (invitedNumStart != null) {
                criteriaInvitedNum.gte(invitedNumStart);
            }
            if (invitedNumEnd != null) {
                criteriaInvitedNum.lte(invitedNumEnd);
            }
            query.addCriteria(criteriaInvitedNum);
        }
        long count = this.mongoTemplate.count(query, UserParticipateActivityInfo.class);
        if (count == 0) {
            log.info("end 【导出报名用户】optName ->{}| activityId ->{} | userId ->{} key->{} 未找到相关数据", optName, activityId,
                    userId,
                    key);
            return;
        }

        ActivityInfo activityInfo = mongoTemplate.findById(activityId, ActivityInfo.class);
        ActivityTaskInfo taskInfo = activityService.findActivityTaskInfo(activityId, TaskBizType.INVITE);
        ActivityTaskInfo taskInfoOrg = activityService.findActivityTaskInfo(activityId, TaskBizType.ORGANIZER);
        ExcelWriter excelWriter = null;
        WriteSheet writeSheet = null;
        String chuSaiQaInfoId = "";
        ActivityQaInfo chuSai = activityQaInfoService.findByActivityIdAndQaNumber(activityId, 1);
        if (Objects.nonNull(chuSai)) {
            chuSaiQaInfoId = chuSai.getId();
        }
        String fileName =
                "活动报名信息" + "-" + activityInfo.getName() + "-" + System.currentTimeMillis() + ExcelTypeEnum.XLSX.getValue();
        String file = "/data/app/file/" + fileName;
        FileExportTask fileExportTask = new FileExportTask();
        fileExportTask.setToken(optName);
        fileExportTask.setBizType("sign-up-info");
        fileExportTask.setStatus(0);
        fileExportTask.setOptUser(optName);
        fileExportTask.setOptUserId(userId);
        fileExportTask.setFileName(fileName);
        fileExportTask.setNum((int) count);
        fileExportTask.setDesc(activityInfo.getName() + "-活动报名信息");
        String fileExportTaskId = fileExportTaskService.create(fileExportTask);
        excelWriter = EasyExcel.write(file, ExportUserActivitySignUpRes.class).build();
        List<ExportUserActivitySignUpRes> exportResult = Lists.newLinkedList();
        try {
            Integer currentPageNo = 1;
            Integer pageSize = 10000;
            while (true) {
                query = new Query();
                query.addCriteria(Criteria.where("activityId").is(activityId).and("joined").is(Boolean.TRUE));
                if (StringUtils.isNotBlank(key)) {
                    query.addCriteria(new Criteria().orOperator(Criteria.where("name").is(key),
                            Criteria.where("mobile").is(key)));
                }
                Pageable pageRequest = PageRequest.of(currentPageNo - 1, pageSize);
                List<UserParticipateActivityInfo> list = this.mongoTemplate.find(query.with(pageRequest),
                        UserParticipateActivityInfo.class);
                if (CollectionUtils.isEmpty(list)) {
                    log.error("end 【导出报名用户】" +
                                    "获取报名数据已结束 optName ->{}| activityId ->{}  currentPageNo - >{}", optName,
                            activityId,
                            currentPageNo);
                    break;
                }
                log.info("【导出报名用户】 currentPageNo - >{}", currentPageNo);
                List<ExportUserActivitySignUpRes> exportList = list.stream().map(userInfoSignUp -> {
                    ExportUserActivitySignUpRes exportUserActivitySignUp = new ExportUserActivitySignUpRes();
                    exportUserActivitySignUp.setName(userInfoSignUp.getName());
                    exportUserActivitySignUp.setUniversity(userInfoSignUp.getUniversityName());
                    exportUserActivitySignUp.setMobile(userInfoSignUp.getMobile());
                    exportUserActivitySignUp.setUniversityId(userInfoSignUp.getUniversityId());
                    exportUserActivitySignUp.setSignUpTime(userInfoSignUp.getSignUpTime());
                    exportUserActivitySignUp.setUserId(userInfoSignUp.getUserId());
                    exportUserActivitySignUp.setActivityId(userInfoSignUp.getActivityId());
                    exportUserActivitySignUp.setQaChuSaiScore(userInfoSignUp.getQaScore().intValue());
                    exportUserActivitySignUp.setGrade(userInfoSignUp.getGrade());
                    exportUserActivitySignUp.setCaName(userInfoSignUp.getCaName());
                    exportUserActivitySignUp.setQq(userInfoSignUp.getQq());
                    exportUserActivitySignUp.setOpenId(userInfoSignUp.getOpenId());
                    exportUserActivitySignUp.setUnionId(userInfoSignUp.getUnionId());
                    exportUserActivitySignUp.setAppId(userInfoSignUp.getAppId());
                    if ("continuous-daka".equals(activityInfo.getType())) {
                        exportUserActivitySignUp.setUserSignInDay(userClockService.getUserContinueSignInDay(userInfoSignUp.getActivityId(),
                                userInfoSignUp.getUserId(), userInfoSignUp.getSignUpTime()));
                    } else {
                        exportUserActivitySignUp.setUserSignInDay(userInfoSignUp.getUserSignInDay());
                    }
                    Boolean existsMobile = userBlackListService.existsByMobile(userInfoSignUp.getMobile());
                    if (existsMobile) {
                        exportUserActivitySignUp.setBackList("是");
                    }
                    return exportUserActivitySignUp;
                }).collect(Collectors.toList());
                //获取学校ID集合，获取省份
                log.info("【导出报名用户】 省份");
                Set<String> universityIdSet =
                        exportList.stream().map(ExportUserActivitySignUpRes::getUniversityId).collect(Collectors.toSet());
                query = new Query();
                query.addCriteria(Criteria.where("id").in(universityIdSet));
                List<UniversityInfo> universityList = this.mongoTemplate.find(query, UniversityInfo.class);
                if (CollectionUtils.isEmpty(universityList)) {
                    continue;
                }
                //设置省份
                exportList.forEach(user -> {
                    UniversityInfo university =
                            universityList.stream().filter(universityInfo -> universityInfo.getId().equals(user.getUniversityId())).findFirst().orElse(null);
                    if (Objects.nonNull(university)) {
                        user.setProvince(university.getProvince());
                    }
                });
                //获取贡献值
                log.info("【导出报名用户】 贡献值");
                List<String> userIdList =
                        exportList.stream().map(ExportUserActivitySignUpRes::getUserId).collect(Collectors.toList());
                List<UserParticipateActivityInfo> userListQuantity = activityService.getUserQuantity(activityId,
                        activityInfo.getType(), taskInfo.getId(), userIdList);
                if (CollectionUtils.isNotEmpty(userListQuantity)) {
                    exportList.forEach(user -> {
                        UserParticipateActivityInfo userParticipate =
                                userListQuantity.stream().filter(userParticipateActivityInfo -> user.getUserId().equals(userParticipateActivityInfo.getUserId())).findFirst().orElse(null);
                        if (Objects.nonNull(userParticipate)) {
                            user.setPoints(userParticipate.getQuantity().intValue());
                        }
                    });
                }
                //设置获取邀请人数
                log.info("【导出报名用户】 邀请人数");
                query = new Query().addCriteria(Criteria.where("invitedByUserId").in(userIdList).and("activityId").is(activityId).and("joinStatus").is(Boolean.TRUE));
                List<UserInviteRecord> userInviteRecordList = mongoTemplate.find(query, UserInviteRecord.class);
                if (CollectionUtils.isNotEmpty(userInviteRecordList)) {
                    Map<String, List<UserInviteRecord>> userInviteCountMap =
                            userInviteRecordList.stream().collect(Collectors.groupingBy(UserInviteRecord::getInvitedByUserId));
                    exportList.forEach(user -> {
                        //通过key（邀请人）获取邀请人数
                        List<UserInviteRecord> userInviteList = userInviteCountMap.computeIfPresent(user.getUserId(),
                                (k, v) -> v);
                        if (CollectionUtils.isNotEmpty(userInviteList)) {
                            user.setInviteCount(userInviteList.size());
                        }
                    });
                    //清除map缓存
                    userInviteCountMap.clear();
                }
                //设置获取邀请人数
                log.info("【设置被邀请人】 被邀请人数");
                if (CollectionUtils.isNotEmpty(userIdList)) {
                    query = new Query().addCriteria(Criteria.where("invitedToUserId").in(userIdList).and("activityId").is(activityId).and("joinStatus").is(Boolean.TRUE));
                    List<UserInviteRecord> invitedToUserList = mongoTemplate.find(query, UserInviteRecord.class);
                    if (CollectionUtils.isNotEmpty(invitedToUserList)) {
                        log.info("【设置被邀请人】 查询已被邀请人数 - >{}", invitedToUserList.size());
                        exportList.forEach(user -> {
                            //可能主动报名，可能被动
                            //个人邀请
                            UserInviteRecord userInvite =
                                    invitedToUserList.stream().filter(userInviteRecord -> userInviteRecord.getInvitedToUserId().equals(user.getUserId()) && userInviteRecord.getTaskId().equals(taskInfo.getId())).findFirst().orElse(null);
                            if (Objects.nonNull(userInvite)) {
                                log.info("【设置被邀请人】个人邀请 ");
                                Query query1 = new Query();
                                query1.addCriteria(Criteria.where("userId").is(userInvite.getInvitedByUserId()).and(
                                        "activityId").is(activityId));
                                UserParticipateActivityInfo userParticipateActivityInfo =
                                        this.mongoTemplate.findOne(query1, UserParticipateActivityInfo.class);
                                if (Objects.nonNull(userParticipateActivityInfo)) {
                                    user.setInviteSource(userParticipateActivityInfo.getMobile());
                                }
                            }
                            if (Objects.nonNull(taskInfoOrg)) {
                                UserInviteRecord userTaskInfoOrg =
                                        invitedToUserList.stream().filter(userInviteRecord -> userInviteRecord.getInvitedToUserId().equals(user.getUserId()) && userInviteRecord.getTaskId().equals(taskInfoOrg.getId())).findFirst().orElse(null);
                                if (Objects.nonNull(userTaskInfoOrg)) {
                                    log.info("【设置被邀请人】承办单位邀请");
                                    ActivityOrganizerInfo activityOrganizerInfo =
                                            activityOrganizerInfoService.find(activityId, userTaskInfoOrg.getInvitedByUserId());
                                    if (Objects.nonNull(activityOrganizerInfo)) {
                                        user.setInviteSource(activityOrganizerInfo.getOrgName());
                                    }
                                }
                            }

                        });
                        invitedToUserList.clear();
                    }
                }
                //是否多级答题
                log.info("【导出报名用户】 多级答题");
                if (activityInfo.getHasMultiQa() || "contest-plus".equals(activityInfo.getType()) || "h5++".equals(activityInfo.getType())) {
                    final int chuSaiNo = 1;
                    final int fuSaiNo = 2;
                    final int jueSaiNo = 3;
                    query = new Query();
                    query.addCriteria(Criteria.where("userId").in(userIdList).and("activityId").is(activityId));
                    List<UserQaInfo> userQaInfoList = mongoTemplate.find(query, UserQaInfo.class);
                    if (CollectionUtils.isNotEmpty(userQaInfoList)) {
                        exportList.forEach(user -> {
                            UserQaInfo chuSaiUserQaInfo =
                                    userQaInfoList.stream().filter(userQaInfo -> chuSaiNo == userQaInfo.getNo() && userQaInfo.getUserId().equals(user.getUserId())).findFirst().orElse(null);
                            if (Objects.nonNull(chuSaiUserQaInfo)) {
                                user.setQaChuSaiScore(chuSaiUserQaInfo.getQaScore().intValue());
                            }
                            UserQaInfo fuSaiUserQaInfo =
                                    userQaInfoList.stream().filter(userQaInfo -> fuSaiNo == userQaInfo.getNo() && userQaInfo.getUserId().equals(user.getUserId())).findFirst().orElse(null);
                            if (Objects.nonNull(fuSaiUserQaInfo)) {
                                user.setQaFuSaiScore(fuSaiUserQaInfo.getQaScore().intValue());
                            }
                            UserQaInfo jueSaiUserQaInfo =
                                    userQaInfoList.stream().filter(userQaInfo -> jueSaiNo == userQaInfo.getNo() && userQaInfo.getUserId().equals(user.getUserId())).findFirst().orElse(null);
                            if (Objects.nonNull(jueSaiUserQaInfo)) {
                                user.setQaJueSaiScore(jueSaiUserQaInfo.getQaScore().intValue());
                            }
                        });
                        userQaInfoList.clear();
                    }
                }
                //导出竞赛活动用户是否答题过初赛练习题
                if (StringUtils.isNotBlank(chuSaiQaInfoId) && "wx-mini-dreambeat-contest".equals(activityInfo.getType())) {
                    query = new Query();
                    query.addCriteria(Criteria.where("userId").in(userIdList).and("qaInfoId").is(chuSaiQaInfoId).and("activityGroupId").is(activityId));
                    List<UserCompetitionQaAnswer> userQaAnswerList = mongoTemplate.find(query, UserCompetitionQaAnswer.class);
                    if (CollectionUtils.isNotEmpty(userQaAnswerList)) {
                        exportList.forEach(user -> {
                            UserCompetitionQaAnswer userQaAnswerInfo = userQaAnswerList.stream().filter(userQaAnswer -> userQaAnswer.getUserId().equals(user.getUserId())).findFirst().orElse(null);
                            if (Objects.nonNull(userQaAnswerInfo)) {
                                List<ActivityQuestionInfo> answersQuestionInfoList = userQaAnswerInfo.getAnswersQuestionInfoList();
                                if (CollectionUtils.isNotEmpty(answersQuestionInfoList)) {
                                    user.setChuSaiQaPractiseCount(answersQuestionInfoList.size());
                                }
                            }
                        });
                        userQaAnswerList.clear();
                    }
                }
//                //设置用户数据
//                log.info("【导出报名用户】 用户数据");
//                List<String> userIdList2 =
//                        list.stream().filter(user2->StringUtils.isBlank(user2.getOpenId())&&StringUtils.isBlank(user2.getUnionId())).map(userParticipateActivityInfo -> userParticipateActivityInfo.getUserId()).collect(Collectors.toList());
//                if(CollectionUtils.isNotEmpty(userIdList2)){
//                    query = new Query().addCriteria(Criteria.where("accountInfoId").in(userIdList2));
//                    query.addCriteria(Criteria.where("appId").is(appId));
//                    List<WechatH5UserPO> userList = mongoTemplate.find(query, WechatH5UserPO.class);
//                    if (CollectionUtils.isNotEmpty(userList)) {
//                        exportList.forEach(user -> {
//                            WechatH5UserPO wechatH5User =
//                                    userList.stream().filter(userH5 -> userH5.getAccountInfoId().equals(user.getUserId())).findFirst().orElse(null);
//                            if (Objects.nonNull(wechatH5User)) {
//                                user.setOpenId(wechatH5User.getOpenId());
//                                user.setUnionId(wechatH5User.getUnionId());
//                                user.setAppId(wechatH5User.getAppId());
//                            }
//                        });
//                        userList.clear();
//                        userIdList2.clear();
//                    }
//                }

                //线下志愿者服务
                log.info("【导出报名用户】 线下志愿者服务");
                if (activityInfo.getHasOffLine() || activityInfo.getHasPraxis() || activityInfo.getHasWorkCollection()) {
                    log.info("start 【导出用户报名】线下志愿服务");
                    query = new Query().addCriteria(Criteria.where("userId").in(userIdList).and("activityId").is(activityId));
                    query.addCriteria(Criteria.where("taskBizType").in(TaskBizType.PRAXIS.name(),
                            TaskBizType.OFF_LINE.name(), TaskBizType.WORK_COLLECTION.name()));
                    List<UserActivityFootPrint> userActivityFootPrints = this.mongoTemplate.find(query,
                            UserActivityFootPrint.class);
                    if (CollectionUtils.isNotEmpty(userActivityFootPrints)) {
                        log.info("start 【导出用户报名】线下志愿服务 count - >{}", userActivityFootPrints.size());
                        Map<String, List<UserActivityFootPrint>> userFootPrintMap =
                                userActivityFootPrints.stream().collect(Collectors.groupingBy(UserActivityFootPrint::getUserId));
                        exportList.forEach(user -> {
                            List<UserActivityFootPrint> userActivityFootPrintList =
                                    userFootPrintMap.computeIfPresent(user.getUserId(), (k, v) -> v);
                            if (CollectionUtils.isNotEmpty(userActivityFootPrintList)) {
                                user.setZhiYuanImgCount(userActivityFootPrintList.size());
                                //审核通过志愿图片
                                long audtiPassCount =
                                        userActivityFootPrintList.stream().filter(userActivityFootPrint -> 1 == userActivityFootPrint.getStatus()).count();
                                user.setZhiYuanAuditPassImgCount((int) audtiPassCount);
                                userActivityFootPrintList.clear();
                            }
                        });
                        userFootPrintMap.clear();
                        userActivityFootPrints.clear();
                    }
                    log.info("end 【导出用户报名】线下志愿服务");
                }
                if (CollectionUtils.isNotEmpty(userIdList)) {
                    userIdList.clear();
                }
                if (CollectionUtils.isNotEmpty(universityIdSet)) {
                    universityIdSet.clear();
                }
                exportResult.addAll(exportList);
                currentPageNo++;
            }
            List<ExportUserActivitySignUpRes> exportResult2 = null;
            Integer skip = 0;
            do {
                exportResult2 = exportResult.stream().skip(skip * MAX_COUNT).limit(MAX_COUNT).collect(Collectors.toList());
                writeSheet = EasyExcel.writerSheet((skip + 1), "报名信息-" + (skip + 1)).build();
                excelWriter.write(exportResult2, writeSheet);
                fileExportTaskService.updateExportNum(fileExportTaskId, exportResult2.size());
                skip++;
            } while (Objects.nonNull(exportResult2) && !exportResult2.isEmpty());
        } catch (Exception e) {
            e.printStackTrace();
            exportResult.clear();
            log.error("end 【导出报名用户】错误", e);
        } finally {
            if (Objects.nonNull(excelWriter)) {
                excelWriter.finish();
            }
            exportResult.clear();
        }
        File newFile = new File(file);
        if (!newFile.exists()) {
            log.error("找不到导出报名信息文件");
            return;
        }
        InputStream in = null;
        try {
            in = new FileInputStream(newFile);
            String url = fileService.uploadFile(in, fileName);
            Query queryTask = new Query().addCriteria(Criteria.where("id").is(fileExportTaskId));
            Update update = new Update();
            update.set("status", 1);
            update.set("url", url);
            update.set("updatedTime", new Date());
            mongoTemplate.updateFirst(queryTask, update, FileExportTask.class);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            log.error("导出报名用户 error", e);
            return;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("导出报名用户 error", e);
            return;
        } finally {
            if (Objects.nonNull(in)) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        log.info("end 【导出报名用户】optName ->{}| activityId ->{} | userId ->{} key->{}", optName, activityId, userId, key);
    }
}
